import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:mi_mang_flutter/model/public/type_model.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/widget/dialog/base_dialog.dart';
import 'package:mi_mang_flutter/widget/dialog/widget_share_dialog.dart';
import 'package:mi_mang_flutter/widget/dialog/widget_type_dialog.dart';

class DialogUtil {
  /// 自定义widget时,需要在销毁时将该属性设置为false
  /// 作用: 防止弹出层多次弹出
  static bool isShowDialog = false;

  /// 消息提示框
  ///
  /// [title] 为空时不显示头部标题
  ///
  /// [onPressed] 确定按钮点击事件
  ///
  /// [barrierDismissible] 是否允许点击背景关闭
  static showDialogMsg(
    BuildContext? context, {
    String title = '提示信息',
    required String msg,
    Function? onCancel,
    Function? onPressed,
    bool barrierDismissible = true,
  }) {
    if (!isShowDialog) {
      isShowDialog = true;
      showElasticDialog(
        context: context!,
        barrierDismissible: barrierDismissible,
        builder: (BuildContext context) {
          return BaseDialog(
            title: title,
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Text(
                msg,
                style: TextStyles.bodyMedium,
                textAlign: TextAlign.center,
              ),
            ),
            onCancel: onCancel,
            onPressed: () {
              /// 点击确定后,先关闭当前弹出框,这里可以返回值
              NavigatorUtils.goBackWithParams(context, true);
              if (onPressed != null) {
                onPressed();
              }
            },
          );
        },
      ).then((val) {
        // 打印返回值
        // print(val);
      });
    }
  }

  /// 弹出类型选择
  ///
  /// [title] 为空时不显示头部标题
  ///
  /// [selectItem] 当前选中项
  ///
  /// [items] 类型列表
  ///
  /// [barrierDismissible] 是否允许点击背景关闭
  ///
  /// [hiddenButton] 是否隐藏底部按钮
  ///
  /// [onPressed] 确定选择事件
  static showTypes(
    BuildContext context, {
    String title = '',
    TypeModel? selectItem,
    List<TypeModel>? items,
    bool barrierDismissible = true,
    bool hiddenButton = false,
    required Function(TypeModel?) onPressed,
  }) {
    if (!isShowDialog) {
      isShowDialog = true;
      showElasticDialog(
        context: context,
        barrierDismissible: barrierDismissible,
        builder: (BuildContext context) {
          return WidgetTypeDialog(
            title: title,
            selectItem: selectItem,
            items: items!,
            hiddenButton: hiddenButton,
            onPressed: onPressed,
          );
        },
      );
    }
  }

  /// 弹出日期选择
  static showPickerDate(
    BuildContext context, {
    DateTime? initialDate,
    DateTime? firstDate,
    DateTime? lastDate,
    DatePickerMode initialDatePickerMode = DatePickerMode.day,
    required Function(DateTime) selectDate,
  }) async {
    if (!isShowDialog) {
      isShowDialog = true;
      var pickerValue = await showDatePicker(
        context: context,
        initialDate: initialDate ?? DateTime.now(),
        initialDatePickerMode: initialDatePickerMode,
        firstDate: firstDate ?? DateTime(1800, 1),
        lastDate: lastDate ?? DateTime.now(),
      );
      if (pickerValue != null) {
        selectDate(pickerValue);
      }
      isShowDialog = false;
    }
  }

  /// 底部弹出选择层(可拓展封装)
  /// DialogUtil.showBottomSheetType(context);
  static showBottomSheetType(BuildContext context) {
    if (!isShowDialog) {
      isShowDialog = true;
      showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext context) {
          return Container(
            color: Colors.transparent,
            margin: EdgeInsets.all(16.0),
            height: 220.0,
            // 自定义拓展内容
            child: Container(
              color: Colors.blue[100],
            ),
          );
        },
      ).then((val) {
        isShowDialog = false;
      });
    }
  }

  /// 弹出分享菜单
  ///
  /// [shareModel] 微信分享的模型,支持(文本,小程序,网页,图片,音乐,视频)
  ///
  /// 目前只支持微信分享,后期加入其它分享是,可通过自定义该模型实现不同类型的分享
  static showShare(BuildContext context, WeChatShareModel shareModel) {
    /// 避免重复弹出
    if (!isShowDialog) {
      isShowDialog = true;
      showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext context) {
          return WidgetShareDialog(
            shareModel: shareModel,
          );
        },
      );
    }
  }

  /// 用于测试弹出提示框中包含文本框,该方法仅供参考
  static showDialogTextFieldTest(
    BuildContext context, {
    String title = '提示信息',
    String hintText = '请输入',
    Function? onPressed,
    bool barrierDismissible = false,
    bool hiddenButton = false,
  }) {
    if (!isShowDialog) {
      isShowDialog = true;
      showElasticDialog(
        context: context,
        barrierDismissible: barrierDismissible,
        builder: (BuildContext context) {
          return BaseDialog(
            title: title,
            hiddenButton: hiddenButton,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: TextField(
                decoration: InputDecoration(
                    contentPadding: const EdgeInsets.symmetric(vertical: 16.0),
                    hintText: hintText,
                    counterText: "",
                    focusedBorder: UnderlineInputBorder(
                        borderSide:
                            BorderSide(color: Divider().color!, width: 0.8)),
                    enabledBorder: UnderlineInputBorder(
                        borderSide:
                            BorderSide(color: Divider().color!, width: 0.8))),
              ),
            ),
            onPressed: () {
              /// 点击确定后,先关闭当前弹出框
              NavigatorUtils.goBack(context);
              if (onPressed != null) {
                onPressed();
              }
            },
          );
        },
      );
    }
  }
}

Future<T?> showElasticDialog<T>({
  required BuildContext context,
  bool barrierDismissible = false,
  WidgetBuilder? builder,
}) {
  final ThemeData theme = Theme.of(context);
  return showGeneralDialog(
    context: context,
    pageBuilder: (BuildContext buildContext, Animation<double> animation,
        Animation<double> secondaryAnimation) {
      final Widget pageChild = Builder(builder: builder!);
      return SafeArea(
        child: Builder(builder: (BuildContext context) {
          return Theme(data: theme, child: pageChild);
        }),
      );
    },
    barrierDismissible: barrierDismissible,
    barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
    barrierColor: Colors.black26,
    transitionDuration: const Duration(milliseconds: 550),
    transitionBuilder: _buildDialogTransitions,
  );
}

Widget _buildDialogTransitions(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child) {
  return FadeTransition(
    opacity: CurvedAnimation(
      parent: animation,
      curve: Curves.easeOut,
    ),
    child: SlideTransition(
      position: Tween<Offset>(begin: const Offset(0.0, 0.2), end: Offset.zero)
          .animate(CurvedAnimation(
        parent: animation,
        curve: animation.status != AnimationStatus.forward
            ? Curves.easeOutBack
            : ElasticOutCurve(0.85),
      )),
      child: child,
    ),
  );
}

/// 默认dialog背景色为半透明黑色，这里修改源码改为透明
showTransparentDialog<T>({
  required BuildContext context,
  bool barrierDismissible = true,
  WidgetBuilder? builder,
}) {
  final ThemeData theme = Theme.of(context);
  return showGeneralDialog(
    context: context,
    pageBuilder: (BuildContext buildContext, Animation<double> animation,
        Animation<double> secondaryAnimation) {
      final Widget pageChild = Builder(builder: builder!);
      return SafeArea(
        child: Builder(
          builder: (BuildContext context) {
            return Theme(data: theme, child: pageChild);
          },
        ),
      );
    },
    barrierDismissible: barrierDismissible,
    barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
    barrierColor: Color(0x00FFFFFF),
    transitionDuration: const Duration(milliseconds: 150),
    transitionBuilder: _buildMaterialDialogTransitions,
  );
}

Widget _buildMaterialDialogTransitions(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child) {
  return FadeTransition(
    opacity: CurvedAnimation(
      parent: animation,
      curve: Curves.easeOut,
    ),
    child: child,
  );
}
